package com.vcourse.service.statistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vcourse.service.api.user.feign.MemberService;
import com.vcourse.service.statistics.entity.Daily;
import com.vcourse.service.statistics.mapper.DailyMapper;
import com.vcourse.service.statistics.service.DailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author Zengsh123
 * @since 2020-06-14
 */
@Service
public class DailyServiceImpl extends ServiceImpl<DailyMapper, Daily> implements DailyService {
    @Resource
    private MemberService memberService;

    @Override
    public void createDailyData(String day) {
        // 是否已有当天数据，有就删掉
        QueryWrapper<Daily> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date_calculated", day);
        baseMapper.delete(queryWrapper);

        // 查询用户注册人数
        int registryNum = (int) memberService.countRegistryNum(day).getData();

        // TODO 查询用户登录人数

        // TODO 查询每日播放视频数

        // TODO 查询每日新增课程数

        Daily dailyData = new Daily();
        dailyData.setDateCalculated(day).setRegisterNum(registryNum);
        baseMapper.insert(dailyData);
    }

    @Override
    public Map<String, Object> getDailyData(String start, String end) {
        Map<String, Object> data = new HashMap<>(4);
        // 查询组装注册人数
        data.put("registerNum", getDailyDataOfOneType(start, end, "register_num"));
        // 查询组装登录人数
        data.put("loginNum", getDailyDataOfOneType(start, end, "login_num"));
        // 查询组装每日播放视频数
        data.put("videoViewNum", getDailyDataOfOneType(start, end, "video_view_num"));
        // 查询组装每日新增课程数
        data.put("courseNum", getDailyDataOfOneType(start, end, "course_num"));
        return data;
    }

    private Map<String, Object> getDailyDataOfOneType(String start, String end, String type) {
        // 查询
        QueryWrapper<Daily> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("date_calculated", type)
                .between("date_calculated", start, end);
        List<Map<String, Object>> dailyList = baseMapper.selectMaps(queryWrapper);

        // 组装数据
        List<String> xData = new ArrayList<>();
        List<String> yData = new ArrayList<>();
        for (Map<String, Object> data : dailyList) {
            xData.add((String) data.get("date_calculated"));
            yData.add((String) data.get(type));
        }
        Map<String, Object> oneTypeData = new HashMap<>(2);
        oneTypeData.put("xData", xData);
        oneTypeData.put("yData", yData);
        return oneTypeData;
    }
}
